<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Models\IntermediaryUser;
use App\Services\RedisFun;
use Illuminate\Http\Request;

class BrokerRank extends Controller
{
    protected $redis;

    protected $brokerKey = 'brokerRank';

    public function __construct()
    {
        $config=[
            'host'=>'127.0.0.1',
            'port'=>'6379',
            'auth'=>''
        ];
        $attr=[];
        $this->redis = new RedisFun($config,$attr);
    }

    public function addRankData()
    {
        // 查询数据库经纪人数据
        $brokerData = IntermediaryUser::getAllData();
        // 删除排名榜的所有数据
        $this->redis->del($this->brokerKey);
        // 批量添加到redis中的sortSet
        foreach ($brokerData as $k => $v) {
            $member = $v['id'].','.$v['real_name'] . ',' . $v['company']['company_name'].','.$v['avatar'];
            //存储到redis的有序集合
            $addBrokerRes = $this->redis->zAdd($this->brokerKey, $v['turnover'], $member);
            if (!$addBrokerRes) return ['code'=>10004,'msg'=>'更新经纪人排名失败','data'=>[]];
        }
        return ['code'=>10001,'msg'=>'更新经纪人排名成功','data'=>[]];
    }

    /**
     * 获取经纪人排名
     */
    public function brokerRankList()
    {
        //获取排行榜从大到小排序
        $brokerListSort = $this->redis->zRevRange($this->brokerKey, 0, 9);
        if (empty($brokerListSort)){
            $this->addRankData();
        }
        $brokerListSort = $this->redis->zRevRange($this->brokerKey, 0, 9);
        $lastBrokerList = [];
        //处理数据
        foreach ($brokerListSort as $k => $v) {
            $v = explode(',', $v);
            $lastBrokerList[] = [
                'rank' => $k + 1,
                'id' => $v[0],
                'name' => $v[1],
                'company_name' => $v[2],
                'avatar'=>$v[3]
            ];
        }
        return ['code'=>10001,'msg'=>'请求成功','data'=>$lastBrokerList];
    }
}
